﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace RakutenProxy.DataConverter.Helper
{
	public class ProductAttributeCombination
	{
		public ProductAttributeCombination()
		{
			Attributes = new List<ProductVariantAttribute>();
		}
		public List<ProductVariantAttribute> Attributes { get; set; }

		public static ProductAttributeCombination Deserialize(string xml)
		{
			if (string.IsNullOrEmpty(xml))
				throw new ArgumentException("xml parameter must not be null or empty");

			try
			{
				var result = new ProductAttributeCombination();

				var xmlRoot = XElement.Parse(xml);
				var attributeNodes = xmlRoot.Elements("ProductVariantAttribute");
				foreach (var attributeNode in attributeNodes)
				{
					try
					{
						var id = attributeNode.Attribute("ID").Value;
						var attributeValue = attributeNode.Element("ProductVariantAttributeValue").Element("Value").Value;
						var attributeId = int.Parse(id);
						var value = int.Parse(attributeValue);
						var productAttribute = new ProductVariantAttribute { ID = attributeId, ProductVariantAttributeValue = new ProductVariantAttributeValue { Value = value } };

						result.Attributes.Add(productAttribute);
					}
					catch (Exception)
					{

					}
				}

				return result;
			}
			catch (Exception)
			{
				
			}

			return null;
		}

		public string Serialize()
		{
			var xmlRoot = new XElement("Attributes");
			foreach (var attribute in this.Attributes)
			{
				var element = new XElement("ProductVariantAttribute", new XAttribute("ID", attribute.ID),
					new XElement("ProductVariantAttributeValue", new XElement("Value", attribute.ProductVariantAttributeValue.Value)));
				xmlRoot.Add(element);
			}

			return xmlRoot.ToString(SaveOptions.None);
		}
	}

	public class ProductVariantAttribute
	{
		[XmlAttribute]
		public int ID { get; set; }

		[XmlElement]
		public ProductVariantAttributeValue ProductVariantAttributeValue { get; set; }
	}

	public class ProductVariantAttributeValue
	{
		[XmlElement]
		public int Value { get; set; }
	}
}
